import { ref } from 'vue'
import { SEARCH_DEBOUNCE } from '../constants'
import type { SearchForm } from '../types'

export const useSearch = () => {
  // 基础搜索表单
  const searchForm = ref<SearchForm>({
    keyword: '',
    deptId: undefined,
    position: undefined,
    mobile: undefined,
    email: undefined,
    status: undefined,
  })

  // 高级搜索表单
  const advancedSearchForm = ref({
    position: '',
    mobile: '',
    email: '',
    status: undefined,
  })

  let searchTimeout: number | null = null

  // 重置搜索
  const resetSearch = () => {
    searchForm.value = {
      keyword: '',
      deptId: undefined,
      position: undefined,
      mobile: undefined,
      email: undefined,
      status: undefined,
    }
    advancedSearchForm.value = {
      position: '',
      mobile: '',
      email: '',
      status: undefined,
    }
  }

  // 基础搜索处理
  const handleSearch = () => {
    if (searchTimeout) {
      clearTimeout(searchTimeout)
    }

    searchTimeout = setTimeout(() => {
      // 基础搜索仅搜索关键词
      // 具体请求由父组件实现
      console.log('执行搜索:', searchForm.value)
    }, SEARCH_DEBOUNCE) as unknown as number
  }

  // 高级搜索处理
  const handleAdvancedSearch = () => {
    // 更新基础搜索表单，合并高级搜索参数
    searchForm.value = {
      ...searchForm.value,
      position: advancedSearchForm.value.position || undefined,
      mobile: advancedSearchForm.value.mobile || undefined,
      email: advancedSearchForm.value.email || undefined,
      status: advancedSearchForm.value.status,
    }
    // 具体请求由父组件实现
    console.log('执行高级搜索:', advancedSearchForm.value)
  }

  return {
    searchForm,
    advancedSearchForm,
    resetSearch,
    handleSearch,
    handleAdvancedSearch,
  }
}
